<!--组织树-->
<template>
  <div id="organizationTree" class="flex-main">
    <!-- 左侧树展示 -->
    <div class="common-title">
      <h2>组织机构
        <el-tooltip class="item" effect="dark" content="刷新" placement="bottom">
          <i class="el-icon-refresh" @click="initOrgCategory" />
        </el-tooltip>
      </h2>
      <span v-if="organizationCategories.length>1" class="options">
        <el-dropdown class="tr color-primary" style="margin-top: 10px;cursor: pointer;font-weight: bold;" size="medium">
          <span class="el-dropdown-link">
            {{ currentSelectCategory.dataDictItemName }}<i class="el-icon-arrow-down el-icon--right" />
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="item in organizationCategories"
              :key="item.dataDictItemCode"
              :class="currentSelectCategory.id===item.id?'color-primary':''"
              @click.native="changeOrganizationCategory(item)">
              {{ item.dataDictItemName }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </span>
    </div>

    <el-input v-if="isFilterInput" v-model="searchValue" placeholder="请输入组织名称" style="margin: 10px 0;" />

    <el-tree
      ref="tree"
      v-loading="treeLoading"
      class="common-el-tree tree-active"
      :data="treeDatas"
      :props="defaultTreeProps"
      node-key="id"
      :default-expand-all="isExpandAll"
      :filter-node-method="onTreeFilter"
      :expand-on-click-node="false"
      :current-node-key="selectedValue"
      @node-click="handleNodeClick">
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <i v-if="data.ext==='1'" class="el-icon-office-building" />
        <i v-else class="el-icon-user" />
        <span class="text">{{ node.data.organizationName }}</span>

      </span>
    </el-tree>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: [String, Array],
      required: false,
      default() {
        return ''
      }
    },

    mode: { type: [Number], default: 1 }, // 默认模式
    isFilterInput: { type: Boolean, default: false }, // 隐藏节点过滤
    isExpandAll: { type: Boolean, default: true }, // 是否展开所有节点
    multiple: { type: Boolean, default: false }, // 多选单选
    isSelectedParent: { type: Boolean, default: true }, // 是否允许选择父节点  默认运行
    defaultCategory: { type: String, default: '01' },
    defaultShowCategory: { type: String, default: 'all' },
    isDept: { type: Boolean, default: true }
  },
  data() {
    return {
      defaultTreeProps: {
        children: 'children',
        label: 'organizationName'
      },
      expandRowKeys: [],
      organizationCategories: [],
      currentSelectCategory: {},
      searchValue: '',
      treeDatas: [],
      expandTreeDatas: [],
      treeLoading: false,
      selectedValue: '',
      fullPathName: [],
      fullPathId: []
    }
  },
  watch: {
    searchValue(val) {
      this.$refs.tree.filter(val)
    },
    selectedValue: function(val) {
      this.$emit('input', typeof (val) === 'string' ? val : val.join(';'))
    },
    orgInfo(val) {
      console.log('监听到组织发生变化：' + JSON.stringify(val))
    },
    value: function(val) {
      setTimeout(() => {
        this.selectedValue = val
      }, 200)
    }
  },
  mounted() {},
  created() {
    if (this.defaultShowCategory !== 'all') {
      if (this.defaultShowCategory.indexOf(this.defaultCategory) === -1) {
        this.$modal.msgWarning('请配置[defaultCategory]属性或属性值与显示的分类不符')
        return
      }
    }
    this.initOrgCategory()
  },
  methods: {
    initOrgCategory() {
      this.$store.dispatch('findDataDictItemByCode', 'organizationCategory').then((res) => {
        this.organizationCategories = res
        if (this.defaultShowCategory !== 'all') {
          this.organizationCategories = []
          res.forEach((item) => {
            if (this.defaultShowCategory.indexOf(item.dataDictItemCode) > -1) {
              this.organizationCategories.push(item)
            }
          })
        }
        if (this.organizationCategories.length > 0) {
          for (var item of this.organizationCategories) {
            if (this.defaultCategory === item.dataDictItemCode) {
              this.currentSelectCategory = item
            }
          }
          this.loadOrganizationTree()
        }
      }).catch((_) => {

      })
    },
    changeOrganizationCategory(item) {
      this.currentSelectCategory = item
      this.loadOrganizationTree()
    },
    async loadOrganizationTree() {
      var organizationCategory = this.currentSelectCategory.dataDictItemCode
      this.treeDatas.length = 0
      this.treeLoading = true
      const response = await this.$store.dispatch('loadOrganizationTree', {
        pid: 0,
        category: organizationCategory,
        type: this.isDept ? null : 1
      })

      this.treeDatas = (response)
      if (response.length > 0) {
        this.$nextTick(() => {
          this.handleNodeClick(response[0], this.$refs.tree.getNode(response[0].id))
        })
      } else {
        this.$emit('selectedOrg', {})
      }

      this.treeLoading = false
    },
    handleNodeClick(data, node) {
      this.$refs.tree.setCheckedKeys([data.id])
      var fullPathId = null
      var fullPathName = null
      this.fullPathId = []
      this.fullPathName = []
      this.fullPathId.push(data.id)
      this.fullPathName.push(data.organizationName)
      this.getParents(node)
      fullPathName = this.fullPathName.reverse().join('')
      fullPathId = this.fullPathId.reverse().join(',')

      var obj = {
        id: data.id,
        name: data.organizationName,
        type: data.type,
        fullPathName: fullPathName,
        fullPathId: fullPathId,
        category: data.organizationCategory,
        treeNumber: data.treeNumber
      }
      this.$emit('selectedOrg', obj)
      this.selectedValue = data.id
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(data.id)
      })
    },
    getParents(node) {
      if (!node.parent) {
        return
      }
      var parentData = node.parent.data
      if (parentData instanceof Array) {
        return
      }
      this.fullPathId.push(parentData.id)
      this.fullPathName.push(parentData.organizationName)
      this.getParents(node.parent)
    },
    /* 节点过滤函数 */
    onTreeFilter(value, data) {
      if (!value) return true
      return data[this.defaultTreeProps.filter] ? data[this.defaultTreeProps.label].indexOf(value) !== -1 || data[this.defaultTreeProps.filter].indexOf(value.toUpperCase()) !== -1 : data[this.defaultTreeProps.label].indexOf(value) !== -1
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" >
  #organizationTree{
    .el-tabs__content{
      height: 0px !important;
      padding: 0px !important;
    }
    .el-tabs--border-card{
      border: 0px;
      box-shadow: none;
    }
    .el-tabs--border-card>.el-tabs__header{
      background-color: #fff;
      border-bottom: 0;
    }
    .tab-container{
      height: 100%;
      overflow-y: auto;
      background: #fff;
      padding: 30px 36px 10px 36px;
    }
    .el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active{
      border: 0;
    }
  }
</style>
